/**
 * Created by Maxwell on 2016/9/26.
 */
"use strict";

var http = require("http"),
    querystring = require("querystring"),
    extend = require("extend"),
    coRequest = require("co-request"),
    Log = require('log'),
    log = new Log('info'),
    _ = require('underscore'),
    request = require('request'),
    coRedis = require('./coRedis');

var transmit = function (options, callbak) {
    var postData = querystring.stringify(options.postData);
    var configuration = {
        hostname: "",
        port: 80,
        path: "",
        method: "GET",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': postData.length
        }
    };

    configuration = extend(true, configuration, options.configuration);
    log.info(configuration);
    var req = http.request(configuration, function (res) {
        var resData = "";
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            resData += chunk;
        });
        res.on('end', function () {
            log.info(JSON.stringify(resData));
            callbak(resData);
        });
    });

    req.on('error', function (e) {
        this.throw(500, "problem with request: " + e.message);
    });

    req.write(postData);
    req.end();
};

/**
 * 自实现的co包装函数
 * @returns {Function}
 */
var dispatch = function () {
    return function (fn) {
        request('http://www.baidu.com', fn);
    }
};

/**
 * request的co包装器
 * @returns {*}
 */
function *transfer(options, next) {
    log.info(options.uri);
    var result = yield coRequest({
        uri: options.uri,
        method: options.method,
        form: options.params,
        // headers: {
        //     'Authorization': 'Basic ' + new Buffer('Crowdfunding-H5:4e1f7857-4fe6-4af5-a0f8-f101d77f40d4').toString('base64')
        // }
        headers: {
            'Authorization': `${options.headerType} ${options.token}`
        }
    });
    log.info(JSON.stringify(result.body));
    try {
        if (typeof result.body === "string") {
            result.body = JSON.parse(result.body);
        }
    } catch (e) {
        result.body = {
            errorCode: "SYS.0000"
        }
    }
    return result
}


/**
 * GET 提交
 * Content-type: application/x-www-form-urlencoded
 * @constructor
 */
function *GET(options) {

}


function *ajaxTransfer(options) {
    var obj = {
        uri: options.uri,
        method: options.method,
        body: options.params,
        json: true,
        headers: {
            'Authorization': `${options.headerType} ${options.token}`
        }
    };
    var result = yield coRequest(obj);
    for (var pa in options.params) {
        if (('' + options.params[pa]).length > 2000) {
            options.params[pa] = 'str is too lang , cut result is ' + ('' + options.params[pa]).substr(0, 100) + '...';
        }
    }
    log.info(options);
    try {
        if (typeof result.body === "string") {
            result.body = JSON.parse(result.body);
        }
    } catch (e) {
        result.body = {
            errorCode: "SYS.0000"
        }
    }
    log.info(JSON.stringify(result.body));
    // if (result.body.errorCode) {
    //var tmpMessage = messageUtil.getMessage(result.body.errorCode);
    //if(tmpMessage){
    //    result.body.errorMessage = tmpMessage;
    //}
    // }
    return result
}


function * commonTransfer(option) {
    var type = option.method;
    var param;
    if(option.headerType){
        param = {
            uri: option.uri,
            method: type,
            headers: {
                'Authorization': `${option.headerType} ${option.token}`
            }
        };
    } else {
        param = {
            uri: option.uri,
            method: type
        };
    }
    if (type.toLocaleLowerCase() == 'get') {
        param["qs"] = option.params;
    } else {
        param["form"] = option.params;
    }
    log.info(param);
    var result = yield coRequest(param);
    log.info(JSON.stringify(result.body));
    return result;
}

module.exports = {
    transmit: transmit,
    dispatch: dispatch,
    transfer: transfer,
    commonTransfer: commonTransfer,
    ajaxTransfer: ajaxTransfer
};